//
//  HLIMKitVoiceDBView.m
//  YueYue
//
//  Created by hulu001 on 2024/1/12.
//

#import "HLIMKitVoiceDBView.h"

@interface HLIMKitVoiceDBView ()

@property (strong,  nonatomic) NSMutableArray *values;
@property (assign,  nonatomic) BOOL drawing;

@end

@implementation HLIMKitVoiceDBView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0];
        self.lineColor = UIColor.whiteColor;
        self.lineSpacing = 3;
        self.lineWidth = 1.5;
        self.minLineHeight = 2;
    }
    return self;
}

- (void)addValue:(NSNumber *)number
{
    if (!self.values) {
        self.values = [NSMutableArray array];
    }
    
    [self.values addObject:number];
    
    if (!self.drawing) {
        self.drawing = YES;
        [self setNeedsDisplay];
    }
}

- (void)reset
{
    [self.values removeAllObjects];
    [self setNeedsDisplay];
}

- (NSInteger)lineNumber
{
    return (self.width + self.lineSpacing) / (self.lineWidth + self.lineSpacing);
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    // 数据准备阶段
    NSArray *tempArray = nil;   // 临时用于绘制的数组
    NSInteger lineNumber = [self lineNumber]; // 计算当前绘制时，需要绘制多少个线
    NSInteger range = lineNumber; // 从数据源取值范围
    
    if (self.values.count <= lineNumber) {
        range = self.values.count;
    }
    tempArray = [self.values subarrayWithRange:NSMakeRange(0, range)];
    NSMutableArray<NSNumber *> *soundArray = [NSMutableArray arrayWithArray:tempArray];
    if (self.values.count > lineNumber) {
        [self.values removeObjectsInRange:NSMakeRange(0, 1)]; // 从数据源删除这一部分已经用于绘制的数据
    }
    
    // 不足的补零
    for (int i = 0; i < (lineNumber - range); i++) {
        [soundArray insertObject:@(0) atIndex:0];
    }
    
    soundArray = [NSMutableArray arrayWithArray:[soundArray reverseObjectEnumerator].allObjects];
    
    
    // 绘制阶段
    // 上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 设置线的顶角样式
    CGContextSetLineCap(context, kCGLineCapSquare);
    // 设置线的连接样式
    CGContextSetLineJoin(context, kCGLineJoinRound);
    // 颜色
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

    
    for (int i = 0; i < lineNumber; i++) {
        CGFloat dbValue = soundArray[i].floatValue;
        
        CGFloat x = (self.lineWidth * 0.5) + (self.lineWidth + self.lineSpacing) * i;
        CGFloat lineHeight = self.minLineHeight + (self.height-self.minLineHeight) * dbValue;
        CGFloat y = (self.height - lineHeight) * 0.5;
        
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x, y + lineHeight);
    }
    
    
    CGContextStrokePath(context);
    
    self.drawing = NO;
}

@end
